// pages/index/shop.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceHeight:0,
    artId:0,
    artName:'',
    menuList:[
      
    ],
    selMenuId:0,
    list: [],
    loading: false,
    haveMore: true,
    is_pull: true,
    page: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          deviceHeight: ((res.windowHeight * 750) / res.windowWidth)
        })
      }
    });

    this.getCate(() => {
      this.getList();
    });
  },

  startLoading: function () {
    if(this.data.haveMore != false) {
      this.setData({
          loading: true,
      })
    }
  },
  stopLoading: function () {
      this.setData({
          loading: false,
      })
  },
  selMenu:function(e){
    let selId = e.currentTarget.id;
    let artArr = selId.split(",")
    if (this.data.artId == artArr[1]) {
      //点击同一个按钮不重新加载
      return;
    }
    this.setData({
      artId: artArr[1],
      artName: artArr[0],
      list: [],
      page: 1,
      haveMore: true
    });
    this.getList();
  },

  getCate(fn = null) {
    let that = this;
    app.http.$ajax({
      url: 'v1.shop/getCate',
      loading: false
    }, {
        success(res) {
          //这是个3维数组
          let list = [...res.data];
          //把第一个设置为默认选择
          that.setData({
            menuList: list,
            artId:list[0].id
          });
          app.util.isFunction(fn) && fn();
        }
      });
  },
  getList: function () {
    let that = this;
    this.startLoading();
    //获取当前分类的下级分类
    app.http.$ajax({
      url: 'v1.shop/getList',
      data: {
        category_id: this.data.artId,
        page: this.data.page,
      },
      loading: false
    }, {
        success(res) {
          that.data.list.push(...res.data.data);
          that.data.page++;
          if (res.data.data.length < res.data.per_page) {
            that.setData({
              list: that.data.list,
              haveMore: false
            });
          } else {
            that.setData({
              list: that.data.list,
            });
          }   
        },
        complete(res) {
          that.stopLoading();
        }
      });
  },
  
  navTocar: function () {
    wx.navigateTo({
      url: '/pages/shop/cart',
    })
  },
})